import axios from 'axios';
import { Message, MessageBox } from 'element-ui';
import store from '@/store';
import router from '@/router';
import { getToken } from '@/utils/auth';

// 创建axios实例
const service = axios.create({
  // eslint-disable-next-line no-undef
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 50000 // 请求超时时间
});

// request拦截器
service.interceptors.request.use(config => {
  let token = '';
  if (store.getters.token) {
    token = getToken();
  }
  config.params = {token: token};
  return config;
}, error => {
  // Do something with request error
  Promise.reject(error);
});

const whiteList = ['/login']; // 不重定向白名单
var single = false;

// respone拦截器
service.interceptors.response.use(
  response => {
    const res = response.data;
    if(res.code == undefined){
      return response;
    }
    if (res.code !== 0) {
      let to = router.currentRoute.path;
      if(whiteList.indexOf(to) === -1){
        if(res.code === 10001 && !single){
          single = true;
          MessageBox.alert(res.msg, '', {
            confirmButtonText: '确定',
            callback: () => {
              store.dispatch('LogOut').then(() => {
                router.replace({path: '/login', query: {redirect: router.currentRoute.fullPath}});
                single = false;
              });
            }
          });
        }
        else if(res.code == 10022){//
          MessageBox.alert(res.code, res.msg);
        }
      }
      return response.data;
    } else {
      return response.data;
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5000
    });
    return Promise.reject(error);
  }
);

export default service;
